package _8_Gorm框架老郭

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

// 创建表对应的结构体

// 书籍类型
type Bookl struct {
	gorm.Model

	Title       string `gorm:"type:varchar(100);unique;not null"`
	Price       int64
	PublishDate *time.Time

	// 一对多
	PublishID int
	Publish   Publish
	// 多对多
	Authors []Author `gorm:"many2many:book_authors;"`
}

// 出版社类型
type Publish struct {
	gorm.Model
	Name string `gorm:"type:varchar(100);unique;not null"`
}

// 作者类型
type Author struct {
	gorm.Model
	Name string `gorm:"type:varchar(100);unique;not null"`
	Age  int
}

func main() {
	// 连接mysql
	dsn := "root:123456@tcp(127.0.0.1:3306)/go_db?charset=utf8mb4&parseTime=True&loc=Local"
	// 创建日志对象
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			//SlowThreshold: time.Second,   // 慢 SQL 阈值
			LogLevel: logger.Info, // Log level
		},
	)

	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger, // 日志配置
	})

	// 自动迁移
	db.AutoMigrate(&Book{})
	db.AutoMigrate(&Publish{})
	db.AutoMigrate(&Author{})

	// (1) 单表添加记录
	//添加三个作者
	authors := []Author{{Name: "yuan", Age: 22}, {Name: "alvin", Age: 25}, {Name: "rain", Age: 32}}
	db.Create(&authors)
	//添加三个出版社
	var publishes = []Publish{{Name: "柠檬出版社"}, {Name: "西瓜出版社"}, {Name: "苹果出版社"}}
	db.Create(&publishes)

	// (2) 关联创建，即一对多和多对多添加记录

	// 案例1
	var book01 = Bookl{
		Title: "乱世佳人",
		Price: 100,
		//PublishID:1,  // 出版社存在的情况
		Publish: Publish{Name: "哈密瓜出版社"},
	}
	db.Create(&book01)

	// 案例2
	var athors = make([]Author, 5)
	db.Where("name in ?", []string{"yuan", "rain"}).Find(&athors)
	fmt.Println(athors)

	var book02 = Bookl{
		Title:     "傲慢与偏见",
		Price:     100,
		PublishID: 2, // 出版社存在的情况
		Authors:   athors,
		// Authors: []Author{{Name: "张三",Age: 22},{Name: "李四",Age: 34}},  // 作者不存在的情况
	}
	db.Create(&book02)
}
